package utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 网络缓存工具类
 * Author：Wbin
 * E_mail：atwbin@163.com
 */

public class NetCacheUtils {

    public static final String LEGALDOCUMENT_ISONECOME = "legaldocument_isonecome";
    /**
     * 成功
     */
    public static final int SUCCESS = 1;
    /**
     * 失败
     */
    public static final int FAIL = 2;
    private Handler handler;
    private ExecutorService service;
    /**
     * 本地缓存的工具类
     */
    private LocalCacheUtils mLocalCacheUtils;
    /**
     * 内存缓存工具
     */
    private MomeryCacheUtils mMomeryCacheUtils;

    public void NetCacheUtils(Handler handler,LocalCacheUtils mlocalCacheUtils,MomeryCacheUtils mMomeryCacheUtils){
        this.handler = handler;
        this.mLocalCacheUtils = mlocalCacheUtils;
        this.mMomeryCacheUtils = mMomeryCacheUtils;
        service = Executors.newFixedThreadPool(10);
    }

    /**
     * 判断是否联网
     * @return
     */
    public static boolean isNetConnected(){
        //怎么联网
        return true;
    }
    public void getBitmapFromUrl(String url,int position){
        service.execute(new MyRunnable(url,position));
    }
    class MyRunnable implements  Runnable{
        private String url;
        private int position;
        public MyRunnable(String url,int position){
            this.url = url;
            this.position = position;
        }

        @Override
        public void run() {
            try {
                HttpURLConnection conn =(HttpURLConnection) new URL(url.toString()).openConnection();
                conn.setRequestMethod("GET");  //连接方式
                conn.setConnectTimeout(5000);
                conn.connect();
                int code = conn.getResponseCode();
                if (code == 200){
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    Message msg = Message.obtain();

                    msg.what = SUCCESS;
                    msg.obj = bitmap;
                    msg.arg1 = position;
                    //发消息
                    handler.sendMessage(msg);
                    //在内存中保存一份
                    mMomeryCacheUtils.putBitmap2Momery(url, bitmap);
                    //在本地sdcard中保存一份
                    mLocalCacheUtils.putBitmap2Local(url,bitmap);
                }
            } catch (IOException e) {
                e.printStackTrace();
                Message msg = Message.obtain();
                msg.arg1 = position;
                //发消息
                handler.sendMessage(msg);
            }
        }
    }
}
